<?php

// +----------------------------------------------------------------------
// | 快递面单打印
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\common\service\faster;

use app\admin\model\base\BaseCourierServiceModel;
use app\admin\model\company\CompanyChannelModel;
use app\admin\model\order\FastLogModel;
use app\admin\model\order\OrderParcelModel;
use app\common\model\admin\service_config\ServiceConfigData;
use app\common\model\admin\service_config\ServiceConfigTabAccount;
use app\common\model\jiyun\base\ChannelModel;
use app\common\service\BaseService;
use think\App;

/**
 * 快递 服务
 * Class AuthService
 * @package app\common\service
 */
class FasterService extends BaseService
{

    public $faster_service = [
        'hualei'  => '',
        'viettel' => '',
    ];

    public $service_arr = [];

    public static $instance ='';

    public $fast_service = '';

    public static function instance()
    {
        //如果不存在实例，则返回实例
        if (empty(self::$instance)) {

            self::$instance = new static();
        }
        return self::$instance;
    }




    /**
     * 定价 （根据包裹信息获得对应的价格）
     * @param       $packing_obj  包裹对象
     * @param array $buy_user  购买人地址
     * @param int   $channel_id  渠道id
     * @return void
     */
    public function pricing($packing_obj, $buy_user, $channel_id)
    {
        // 获得对应的service对象
        $service_obj = $this->getService($channel_id);


        // 设置需要的参数 发送请求
        $res = $service_obj->pricing($packing_obj, $buy_user);

        $this->insertLog($order_obj, 'pricing_data',$res);

        return $res;

    }

    /**
     * 创建订单
     *
     * @param OrderParcelModel $order_obj
     * @return false
     */
    public function createOrder(OrderParcelModel $order_obj)
    {
        // 获得对应的service对象
        $service_obj = $this->getService($order_obj->channel_id);

        // 设置需要的参数 // 发送请求
        $fast_order_obj = $service_obj->createOrder();

        $this->insertLog($order_obj, 'order_data', $this->result, $fast_order_obj->express_no);

        return $fast_order_obj;

    }

    /**
     * 获得轨迹
     *
     * @return void
     */
    public function getTracking(OrderParcelModel $order_obj)
    {
        // 获得对应的service对象
        $service_obj = $this->getService($order_obj->channel_id);
        if (!$service_obj) {
            $this->error_msg = '未找到对应的服务';
            return false;
        }
        // 设置需要的参数 // 发送请求
        $data = $service_obj->setData($order_obj)->getTracking();
        $this->result = $service_obj->getResult();

        if (!$data) {
            $this->error_msg = $service_obj->getErrorMsg();
            return false;
        }

        return $data;
    }
    /**
     * 获得单号
     *
     * @param $order_id
     * @return false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    /*public function getOrderNoById ($order_id = 0)
    {
        $fast_obj = FastLogModel::where('parcel_id', $order_id)->find();

        if ($fast_obj) {
            return $fast_obj->fast_order_no;
        }
        $this->error_msg = '请先去创建三方订单';
        return false;
    }*/



    /**
     * 获得打印信息
     *
     * @return void
     */
    public function getPrintLinkByFastNo($fast_no)
    {
        $fast_obj = FastLogModel::where('fast_order_no', $fast_no)->find();

        if ($fast_obj) {
            return $fast_obj->fast_order_no;
        }
        $this->error_msg = '请先去创建三方订单';
        return false;

        // 获得对应的service对象
        $service_obj = $this->getService($channel_id);

        if (!$service_obj) {
            $this->error_msg = '未找到对应的服务';
            return false;
        }

        // 设置需要的参数 // 发送请求
        $res = $service_obj->getPrintData();

        $this->result = $service_obj->getResult();

        if (!$res) {
            $this->error_msg = $service_obj->getErrorMsg();
            return false;
        }

        return $res;
    }

    /**
     * 获得对应的服务对象， 用于其特有的接口使用
     */
    public function getFasterService()
    {
        return $this->fast_service;
    }


    /**
     * 获得对应服务
     *
     * @param $channel_id
     * @return false
     */
    private function getService($channel_id)
    {

        if ( isset($this->service_arr[$channel_id]) ) {
            return $this->service_arr[$channel_id];
        }

        $channel_obj = ChannelModel::mk()->where('id', $channel_id)->find();

        if (!$channel_obj || $channel_obj->express_id) {

            $this->error('渠道异常');
        }
        // 获得对应的 快递配置
        $tab_account_obj = ServiceConfigTabAccount::mk()->where('id', $channel_obj->express_id)->find();

        $config_obj      = ServiceConfigData::mk()->where('account_group_id', $tab_account_obj->id)->where('account_id', $tab_account_obj->account_id)->column('value', 'code');

        if(!$config_obj) {
            $this->error('未配置当前快递');
        }

        if ( !isset($this->faster_service[$tab_account_obj->group]) ) {
            $this->error('未配置当前快递');
        }

        $faster_service =  $this->faster_service[$tab_account_obj->group];

        $fast_service_obj = new $faster_service();

        $fast_service_obj->setConfig($config_obj);

        $this->service_arr[$channel_id] = $fast_service_obj;

        return $fast_service_obj;
    }


    private function insertLog ($order_obj, $field, $value, $fast_order_no='')
    {
        $fastLog_obj = FastLogModel::where('parcel_id', $order_obj->id)->where('channel_id', $order_obj->channel_id)->where('consolidation_id', $order_obj->consolidation_id)->find();

        if (!$fastLog_obj) {
            $fastLog_obj = new FastLogModel();

            $fastLog_obj->fast_order_no     = $fast_order_no;
            $fastLog_obj->parcel_id         = $order_obj->id;
            $fastLog_obj->channel_id        = $order_obj->channel_id;
            $fastLog_obj->consolidation_id  = $order_obj->consolidation_id;
            $fastLog_obj->consolidation_no  = $order_obj->consolidation_no;
            $fastLog_obj->express_no        = $order_obj->express_no;
        }

        if (empty($update) == false) {

            $fastLog_obj->$field = is_array($value) ? json_encode($value) : $value;

            $fastLog_obj->save();
        }


    }



}